/*
 * @Author       : 邱狮杰
 * @Date         : 2021-05-19 15:38:01
 * @LastEditTime : 2021-05-20 16:59:30
 * @FilePath     : /wedding-dress-selection/src/hook/http.ts
 * @Description  : http
 */
import { useRef, MutableRefObject } from 'react'
import axios, { CancelTokenStatic } from 'axios'
import { useMounted, useUserInfoForReducer } from './index'
import { getQueryVariable, getLocal, setLocal, SynchronizationAwaitError } from '../utils/index'
import { BaseRequest } from '../http/index'
import { OPENID } from '../reducer/userInfo'
// import { OPENID } from '../reducer/userInfo'

export function useCannelRef(): MutableRefObject<CancelTokenStatic> {
  return useRef(axios.CancelToken)
}

export function useGetOpenid(notCode: () => void) {
  const { userInfoState, userInfoDispatch } = useUserInfoForReducer()
  useMounted(async () => {
    const codeOnURL = getQueryVariable('code')
    // have openid
    if (userInfoState.openId || getLocal(OPENID)) return
    if (!userInfoState.openId && codeOnURL) {
      //you openid code
      const [err, res] = await SynchronizationAwaitError(BaseRequest({ url: '/wechat-auth', params: { code: getQueryVariable('code') } }), e => {
        return e.data
      })
      if (!err) {
        setLocal(OPENID, res.data.openid)
        userInfoDispatch({ type: 'reset', data: { openId: res.data.openid } as any })
      }
    } else {
      // openid code
      // to url
      notCode()
      window.location.href = 'http://auring-bridal.com/invitation-info?invitation_id=3&authorize=1 '
    }
  })
}
